window.app=window.app||{};
var params={left:0,top:0,currentX:0,currentY:0,flag:false};var getCss=function(b,a){return b.currentStyle?b.currentStyle[a]:document.defaultView.getComputedStyle(b,false)[a]};var startDrag=function(a,b){if(getCss(b,"left")!=="auto"){params.left=getCss(b,"left")}if(getCss(b,"top")!=="auto"){params.top=getCss(b,"top")}a.onmousedown=function(c){params.flag=true;if(!c){c=window.event;a.onselectstart=function(){return false}}var d=c;params.currentX=d.clientX;params.currentY=d.clientY};document.onmouseup=function(){params.flag=false;if(getCss(b,"left")!=="auto"){params.left=getCss(b,"left")}if(getCss(b,"top")!=="auto"){params.top=getCss(b,"top")}};document.onmousemove=function(h){var i=h?h:window.event;if(params.flag){var d=i.clientX,c=i.clientY;var g=d-params.currentX,f=c-params.currentY;b.style.left=parseInt(params.left)+g+"px";b.style.top=parseInt(params.top)+f+"px"}}};

app.log=function(msg)
{	
	var debug=true;
	if(debug)
	{
		console.log(msg);
	}
}
app.bbs=
{
	replyPostUrl:'/bbs/replyPost',
	createPostUrl:'/bbs/createPost',
	loginUrl:'/bbs/tpl/login',

	init:function()
	{
		this.loadjs();
	},
	start:function()
	{
		this.listener();
		this.online();
		this.waterfall();
		jQuery(".slideTxtBox").slide();
		var ary = location.href.split("&");
		jQuery(".slideBox").slide( { mainCell:".bd ul", effect:ary[1],autoPlay:ary[2],trigger:ary[3],easing:ary[4],delayTime:ary[5],mouseOverStop:ary[6],pnLoop:ary[7] });
	

	},
	online:function()
	{
		if(!$.cookie('token'))
		{
			return;
		}
		if(window.localStorage)
		{
			setTimeout(function(){
				var online=localStorage.getItem('online');
				var now=new Date().getTime();
				if(online)//设定过
				{
					if(now-online>1200*1000) //距上次声明在线超过20分钟
					{
						$.get('/bbs/online/h5',function(){
							localStorage.setItem('online',now); //声明设定时间
						});
					}
				}
				else //没有设定过
				{
					localStorage.setItem('online',now);
				}
			},5000);	
		}
		else
		{
			setTimeout(function(){
				$.get('/bbs/online/h0',function(){
					app.log('online event');
				});
			},9000);
		}
	},
	listener:function()
	{
		$('.index-banner').backstretch(["http://suconghou.sinaapp.com/649e8b9726c75b3a0328eff60c6a1c75.jpg","http://ww1.sinaimg.cn/large/4eda25f5gw1ea6i91dvflj20xc0go0ut.jpg"],{speed:800},{duration:2000});
 		this.postListener();
 		$(document).on('click','.load-reply',function(){
 			alert('load reply');
 		});
	},
	postListener:function() ///帖子正文页的处理
	{
		$('#comment-btn').click(function(){
			var postId=$('.post-title').data('postid');
			var content=$('#comment-text').val();
			if(postId&&content)
			{
				app.bbs.replyPost(postId,content);
			}
		});
	},
	waterfall:function()
	{
		$(document).on('mousewheel','.mfp-img',function(){wheelimg(this);});
		function wheelimg(o) //放大缩小
		{
			var size=$(o).data('size')||1;
			size+=event.wheelDelta/200;
			if (size>1)
			{ 
				if(size>5)size=5;
			}
			else
			{
				size=1;
			}
			$(o).css({'-webkit-transform':'scale('+size+')','transform':'scale('+size+')'});
			$(o).data('size',size);
			return false;
		}
		 (function ($) {
      	  var $tiles = $('#tiles'),
          $handler = $('li', $tiles),
          page = 1,
          isLoading = false,
          apiURL = '/bbs/imgurl',
          lastRequestTimestamp = 0,
          fadeInDelay = 1000,
          $window = $(window),
          $document = $(document);

	      // Prepare layout options.
	      var options = {
	        autoResize: true, // This will auto-update the layout when the browser window is resized.
	        container: $('#tiles'), // Optional, used for some extra CSS styling
	        offset: 4, // Optional, the distance between grid items
	        itemWidth: 310 // Optional, the width of a grid item
	      };

	     $('#tiles').magnificPopup({
         delegate: 'li:not(.inactive) a',
         preloader: true,
         closeBtnInside: false,
         mainClass: 'mfp-no-margins mfp-with-zoom',
         fixedContentPos: true,
         type: 'image',
         image:{verticalFit: true},
         removalDelay: 100,
         zoom: {
    			enabled: true, // By default it's false, so don't forget to enable it
			    duration: 100, // duration of the effect, in milliseconds
    			easing: 'ease-in-out', // CSS transition easing function 
			    // The "opener" function should return the element from which popup will be zoomed in
			    // and to which popup will be scaled down
			    // By defailt it looks for an image tag:
			    opener: function(openerElement) {
			      // openerElement is the element on which popup was initialized, in this case its <a> tag
			      // you don't need to add "opener" option if this code matches your needs, it's defailt one.
			      return openerElement.is('img') ? openerElement : openerElement.find('img');
			    }
  			},
        gallery: {
          enabled: true,
          preload: [0,2]
        }
      });

	      	/**
		       * When scrolled all the way to the bottom, add more tiles.
		       */
	    function onScroll(event)
	    {
	        // Only check when we're not still waiting for data.
	        if (!isLoading)
	        {
	          // Check if we're within 200 pixels of the bottom edge of the broser window.
	          var closeToBottom = ($window.scrollTop() + $window.height() > $document.height() - 200);
	          if (closeToBottom)
	          {
	            // Only allow requests every second
	            var currentTime = new Date().getTime();
	            if (lastRequestTimestamp < currentTime - 1000)
	            {
	              lastRequestTimestamp = currentTime;
	              loadData();
	            }
	          }
	        }
	    };

	      /**
	       * Refreshes the layout.
	       */
	    function applyLayout($newImages)
	    {
	        options.container.imagesLoaded(function() {
	          // Destroy the old handler
	          if ($handler.wookmarkInstance) {
	            $handler.wookmarkInstance.clear();
	          }

	          // Create a new layout handler.
	          $tiles.append($newImages);
	          $handler = $('li', $tiles);
	          $handler.wookmark(options);

	          // Set opacity for each new image at a random time
	          $newImages.each(function(){
	            var $self = $(this);
	            window.setTimeout(function(){
	              $self.css('opacity', 1);
	            }, Math.random() * fadeInDelay);
	          });
	        });
	    };

	      /**
	       * Loads data from the API.
       */
        function loadData() {
         isLoading = true;
         $('#loaderCircle').show();

         $.ajax({
          url: apiURL,
          dataType: 'json', // Set to jsonp if you use a server on a different domain and change it's setting accordingly
          data: {page: page}, // Page parameter to make sure we load new data
          success: onLoadData
         });
       };

	      /**
	       * Receives data from the API, creates HTML for images and updates the layout
	       */
	      function onLoadData(response) {
	        isLoading = false;
	        $('#loaderCircle').hide();
	        // Increment page index for future calls.
	        page++;
	        // Create HTML for the images.
	        var html = '',
	            data = response.data,
	            i = 0, length = data.length, image, opacity,
	            $newImages;

	        for (; i < length; i++) {
	          image = data[i];

	          html += '<li>';
	          html += '<a target="_blank" href="'+image.image+'" title="'+image.title+'">';
	          // Image tag (preview in Wookmark are 200px wide, so we calculate the height based on that).
	          html += '<img src="'+image.preview+'" width="200" height="'+Math.round(image.height/image.width*200)+'">';
	          html += '</a>';
	          // Image title.
	          html += '<p>'+image.title+'</p>';
	          html += '</li>';
	        }

	        $newImages = $(html);

	        // Disable requests if we reached the end
	        if (response.message == 'No more pictures')
	        {
	          $document.off('scroll', onScroll);
	        }

	        // Apply layout.
	        applyLayout($newImages);
	      };

	      // Capture scroll event.
	      $document.on('scroll', onScroll);
	      // Load first data from the API.
	      loadData();
	    })(jQuery);


	},
	loadjs:function()
	{
		head.load("http://cdn.staticfile.org/jquery/1.11.1/jquery.min.js", 
				"http://cdn.staticfile.org/jquery-backstretch/2.0.4/jquery.backstretch.min.js",
				"http://cdn.staticfile.org/jquery-cookie/1.4.1/jquery.cookie.min.js",
				"http://code.jquery.com/jquery-migrate-1.1.1.js",
				"/static/js/jquery.pjax.js",
				"/static/js/jquery.wookmark.min.js",
				"/static/js/jquery.imagesloaded.js",
				"/static/js/jquery.magnific-popup.min.js",
				"/static/js/jquery.anyDrag.min.js",
				"/static/js/jquery.jsmartdrag.js",
				"/static/js/jquery.SuperSlide.2.1.1.js",
				"/static/js/jquery.tipMessage.js",function(){
					app.bbs.start();
			});
	},
	login:function()
	{
		$('#login').load(this.loginUrl);
	},
	autologin:function()
	{
		if($.cookie('userid')&&$.cookie('username')&&$.cookie('token'))
		{
			$.get('/login/autologin');
		}

	},
	reg:function()
	{	
		$('#login').load(this.loginUrl,function(){
			$('#to-reg').click();
		});
	},
	//回复帖子
	replyPost:function(postId,content)
	{
		$.post(this.replyPostUrl,{postId:postId,content:content},function(data){
			if(data.code==0)
			{
				location.reload();
			}
			else
			{
				$.tipMessage(data.msg);
			}
		},'json');
	},
	//创建主题
	createPost:function(forumId,title,content)
	{
		$.post(this.createPostUrl,{forumId:forumId,title:title,content:content},function(data){
			if(data.code!=0)
			{
				$.tipMessage(data.msg);
			}
		},'json');
	},
	reply:function(id)
	{
		if(!app.bbs.commentBox)
		{
			app.bbs.commentBox=$('.comment-box');
		}
		$('#reply-'+id).find('.reply-bottom').append(app.bbs.commentBox);
	},
	up:function()
	{

	},
	down:function()
	{

	}

}

app.bbs.init();


app.richtext=
{
	init:function()
	{
		
	},
	listener:function()
	{
		$(document).on('click','#comment-img',function()
		{
			$(this).find()

		});
	}

}
